/*
 * RefresherThread.java
 *
 * Created on 16  2007, 10:43
 *Note: This source code is protected under the This software is licensed under the CC-GNU GPL.
 */
package OpenToday;

import OpenToday.Configuration.OpenTodayConfiguration;


/**
 * thread class implements runnable
 * <p>
 * methods are synchronized like described in a java me book isbn 978-3-446-41376-4
 * @author Menny Even Danan (c) 2007. Note: This source code is protected under the This software is licensed under the CC-GNU GPL.
 */
public class RefresherThread implements Runnable {

    private boolean m_running = true;
    private boolean m_paused = false;
    private final IManager m_mainObject;
    private Thread m_thread = null;
    private boolean m_mustRefresh = false;

    /** Creates a new instance of RefresherThread
     * @param main the OpenTodayMain class
     */
    public RefresherThread(IManager main) {
        m_mainObject = main;
    }

    /**
     * start thread inf not done before
     */
    public synchronized void start() {
        if (m_thread == null) {
            m_thread = new Thread(this);
            m_thread.start();
        }
    }



    /**
     * refresh today screen and wait
     * wait interval is configered in m_refreshInSeconds
     * stop is called if interrupted
     */
    public void run() {
        try {
            while (m_running) {
                synchronized (this) {
                    if (!m_paused) {
                        m_mainObject.RefreshTodayScreen();
                    }
                    //refresh event list in milliseconds
                    wait(OpenTodayConfiguration.getInstance().get_RefreshEventsListInMilliseconds());
                }
            }
        } catch (InterruptedException ex) {
            stop();
            //ex.printStackTrace();
        }
    }

    /**
     * set paused variable
     */
    public synchronized void pause() {
        m_paused = true;
    }


    /**
     * set paused variable to false and notifyAll
     */
    public synchronized void resume() {
        m_paused = false;
        m_mustRefresh = true;
        notifyAll();
    }

    /**
     * set running to false and thread.interrupt();
     */
    public synchronized void stop() {
        m_running = false;
        if (m_thread != null) {
            m_thread.interrupt();
        }
    }

}
